package pl.edu.mimuw.mas.agent.behaviour.helicopter.areaassignment;

import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.UngroundedException;
import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.mimuw.mas.agent.HelicopterAgent;
import pl.edu.mimuw.mas.agent.behaviour.ServerBehaviour;
import pl.edu.mimuw.mas.chart.Area;

/**
 * Zachowanie nasłuchujące obszaru poszukiwań od lidera. Po otrzymaniu obszaru
 * poszukiwań zaczyna patrolowanie wykonując metodę doPatrol agenta.
 */
public class ListenSearchAreaBehaviour extends ServerBehaviour {
	private static final long serialVersionUID = 8660639912056314045L;
	private final Logger logger = LoggerFactory.getLogger(getClass());

	public ListenSearchAreaBehaviour(HelicopterAgent agent, AID leaderAID) {
		super(agent);
		MessageTemplate mt = MessageTemplate.and(
				MessageTemplate.and(
						MessageTemplate.MatchSender(leaderAID), 
						MessageTemplate.MatchConversationId(HelicopterAgent.HELICOPTER_ASSIGN_SEARCH_AREA_CONV)
						),
				MessageTemplate.MatchPerformative(ACLMessage.INFORM)
				);
		setMessageTemplate(mt);
	}
	
	public boolean doAction(ACLMessage msg, ACLMessage reply) throws UngroundedException, CodecException, OntologyException, UnreadableException, IOException {
		HelicopterAgent ha = (HelicopterAgent) myAgent;
		Area area = (Area) msg.getContentObject();
		
		int[] realArea = area.getArea();
		logger.info("{}: Dostalem obszar poszukiwań ((" + realArea[Area.X0]
				+ ", " + realArea[Area.Y0] + ")(" + realArea[Area.X1] + ", "
				+ realArea[Area.Y1] + "))", myAgent.getName());

		ha.log("Dostalem obszar poszukiwań ((" + realArea[Area.X0]
				+ ", " + realArea[Area.Y0] + ")(" + realArea[Area.X1] + ", "
				+ realArea[Area.Y1] + ")");		
		
		// Patroluj
		ha.setSearchArea(area);
		ha.doPatrol();
		
		stop();
		return false;
	}	
}
